package com.invest.task.riskfree;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.invest.common.exception.ServiceException;
import com.invest.domain.entity.RiskFree;
import com.invest.mapper.RiskFreeMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

/**
 * 获取十年期无风险利率
 *
 * @projectName: invest
 * @author: yuch
 * @description: TODO
 * @date: 2025/1/16 16:16
 */


@Component
@Slf4j
public class RiskFreeRate {
    @Autowired
    private RiskFreeMapper riskFreeMapper;

    @Value("${riskfree.url}")
    public String baseurl;


    public void start() throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost request = new HttpPost(baseurl);
            request.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.setHeader("Accept-Encoding", "gzip, deflate, br, zstd");
            request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.setHeader("Origin", "https://iftp.chinamoney.com.cn");
            request.setHeader("Priority", "u=1, i");
            request.setHeader("Referer", "https://iftp.chinamoney.com.cn/chinese/sddsintigy/");
            request.setHeader("Sec-Ch-Ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"");
            request.setHeader("Sec-Ch-Ua-Mobile", "?0");
            request.setHeader("Sec-Ch-Ua-Platform", "\"Windows\"");
            request.setHeader("Sec-Fetch-Dest", "empty");
            request.setHeader("Sec-Fetch-Mode", "cors");
            request.setHeader("Sec-Fetch-Site", "same-origin");
            request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36");
            request.setHeader("X-Requested-With", "XMLHttpRequest");

            // 设置请求体

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String nowDay = simpleDateFormat.format(new Date());

            StringBuffer buf = new StringBuffer();
            buf.append("lang=CN&" +
                    "startDate=" + nowDay + "&" +
                    "endDate=" + nowDay + "&" +
                    "pageNum=1&" +
                    "pageSize=10");
            StringEntity params = new StringEntity(buf.toString(), "UTF-8");
            request.setEntity(params);

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("Status Code: " + statusCode);
                if (statusCode != 200) {
                    throw new ServiceException("获取无风险利率请求失败！");
                }
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(responseBody);
                JSONArray jsonArray = (JSONArray) jsonObject.get("records");
                if (jsonArray.isEmpty()) {
                    log.info("获取的请求为空！");
                    return;
                }
                RiskFree riskFree1 = JSON.parseObject(jsonArray.get(0).toString(), RiskFree.class);
                if (riskFree1 != null) {
                    String time = riskFree1.getTime();
                    RiskFree riskFree2 = riskFreeMapper.selectByTime(time);

                    if (riskFree2 != null) {
                        riskFree2.setUpdateTime(new Date());
                        riskFreeMapper.updateRiskFree(riskFree2);
                    } else {
                        riskFree1.setUpdateTime(new Date());
                        riskFreeMapper.insertRiskFree(riskFree1);
                    }
                }
            }
        } catch (IOException e) {
            log.error(e + "==时间：" + LocalDate.now());
            throw e;
        }

    }
}
